import { getStore } from "@/store";
import type { User, Customer } from "../types/user";
import { request } from "@/service/request/request";
import { decryptData, encryptData } from "@/utils/crypto";

/**
 *  持久化token
 *  加密后存储在localStorage中
 * @param token
 */
export const persistToken = (token: string): void => {
    localStorage.setItem("sys-token", encryptData(token));
};

/**
 *  从localStorage获取token
 *  解密后返回
 * @returns 解密后的token
 */
export const getToken = (): string | null => {
    const encryptedToken = localStorage.getItem("sys-token");
    return encryptedToken ? decryptData(encryptedToken) : null;
};

/** 删除localStorage中的token */
export const removeToken = (): void => {
    localStorage.removeItem("sys-token");
};

/**
 * 自动登录
 * 从localStorage中获取token，然后发送请求获取用户信息
 * @returns 登录成功返回true，否则返回false
 */
export const autoLogin = async () => {
    const sys_token = getToken();
    if (!sys_token) {
        localStorage.clear();
        throw new Error("No token found");
    }

    try {
        const userStore = getStore("user");

        const { user, token } = await request<{
            user: User | Customer;
            token: string;
        }>(
            "/user/auto_login_user",
            "post",
            {
                token: sys_token,
            },
            {
                loading: false,
            }
        );
        persistToken(token);
        userStore.setUserInfo(user);
        userStore.setIsAuthenticated(true);
    } catch (error) {
        console.log(error);
        throw error;
    }
};
